package it.marcelate.rcp.jdtutil.ui.actions;

import it.marcelate.rcp.jdtutil.util.FindAndReplaceMemberSupport;
import it.marcelate.rcp.jdtutil.util.FindAndReplaceMemberSupportImpl1;

import java.util.Iterator;
import java.util.List;

import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

/**
 * 
 * @author demarcom
 *
 * @see http://www.jdg2e.com/ch27.jdt/doc/index.html (The Java Developers Guide to Eclipse # ch. 27)
 * @see http://www.jdg2e.com/jdg2e_CD_for_eclipse321.zip (download examples)
 *
 * TO DO: replacement (SEE ABOVE LINK)
 *
 * {@link http://www.jdg2e.com/jdg2e_CD_for_eclipse321/plug-in_development/examples/com.ibm.jdg2e.jdt/src-extension/com/ibm/jdg2e/jdt/extras/MakeIMemberPrivateAction.java}
 *
 *
 */


public abstract class FindAndReplaceMethodBaseAction implements IWorkbenchWindowActionDelegate {

  protected void processCompilationUnit(ICompilationUnit cu) {
    try {
      
      ASTParser astParser = ASTParser.newParser(AST.JLS3);
      astParser.setSource(cu);
      ASTNode cuNode = astParser.createAST(null);
      AST ast = cuNode.getAST();
      ASTRewrite rewriter = ASTRewrite.create(ast);

      /**
       * TO DO: input pattern
       */
      FindAndReplaceMemberSupport findAndReplaceSupport = new FindAndReplaceMemberSupportImpl1("getValore");
      List<BodyDeclaration> matchingMembers = findAndReplaceSupport.getMemberFinder((CompilationUnit)cuNode).getBodyDeclarations();
      for (Iterator<BodyDeclaration> it = matchingMembers.iterator(); it.hasNext();) {
        findAndReplaceSupport.process(it.next(), ast, rewriter);
      }
      
      IBuffer buffer = cu.getBuffer();
      
      IDocument doc = new Document(buffer.getContents());
      TextEdit textEdit = rewriter.rewriteAST(doc, null);
      textEdit.apply(doc);
      
      buffer.replace(0, buffer.getLength(), doc.get());
      
    } catch (Exception ex) {
      ex.printStackTrace();
    } 
    
  }

}
